package com.crazy.shell.server.base;

import com.crazy.shell.api.base.BaseProvider;
import com.crazy.shell.common.persistent.dao.entity.BaseEntity;
import com.crazy.shell.common.persistent.service.BaseService;
import com.crazy.shell.common.result.ActionResult;
import com.crazy.shell.dao.bean.BaseEnum;
import com.crazy.shell.service.company.CompanyServiceImpl;
import com.sun.xml.internal.rngom.parse.host.Base;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.Date;

/**
 * shell-crm
 * 创建人 : creazier.huang
 * 创建时间 : 16/7/7.
 */
public abstract class BaseProviderImpl<T extends BaseEntity> implements BaseProvider<T> {


    private static final Logger logger = LoggerFactory.getLogger(BaseProviderImpl.class);

    private BaseService<T> baseService;

    @Override
    public ActionResult add(T t) {
        Assert.notNull(t);
        logger.info( " add {}" , t);
        ActionResult result = new ActionResult();
        result.setMessages("系统异常,请联系管理员");
        t.setEnable(BaseEnum.EnableEnum.Enable.getKey());
        t.setCreateTime(new Date());
        int row = baseService.insert(t);
        if(row == 0)
            return result;
        result.setSuccess(true);
        result.attach("data",row);
        return result;
    }

    @Override
    public ActionResult update(T t) {
        Assert.notNull(t);
        logger.info( " update {}" , t);

        ActionResult result = new ActionResult();
        result.setMessages("系统异常,请联系管理员");
        t.setModifyTime(new Date());

        int row = baseService.update(t);
        if(row == 0)
            return result;
        result.setSuccess(true);
        result.attach("data",row);
        return result;
    }

    @Override
    public ActionResult getById(Integer id) {
        Assert.notNull(id);
        logger.info( " getById {}" , id);

        ActionResult result = new ActionResult();
        result.setMessages("系统异常,请联系管理员");

        T t = baseService.getByKey(id);
        if(t == null)
            return result;
        result.setSuccess(true);
        result.attach("data",t);
        return result;
    }

    @Override
    public ActionResult deleteById(Integer id) {
        Assert.notNull(id);
        logger.info( " deleteById {}" , id);

        ActionResult result = new ActionResult();
        result.setMessages("系统异常,请联系管理员");
        T t = baseService.getByKey(id);
        if(t == null){
            result.setMessages("找不到 id : "+id);
            return result;
        }
        int row = baseService.updateSelective(t);
        if(row == 0)
            return result;
        result.setSuccess(true);
        result.attach("data",row);
        return result;
    }



    public abstract BaseService<T> getBaseService();

    public void setBaseService(BaseService<T> baseService) {
        this.baseService = baseService;
    }
}
